const { app, BrowserWindow, ipcMain, Tray, Menu } = require('electron');
const { default: installExtension, REDUX_DEVTOOLS, REACT_DEVELOPER_TOOLS } = require('electron-devtools-installer');
const path = require('path');

const isDev = require('electron-is-dev');
let win, tray, menu;

function createWindow () {

 // 打开窗口

  win = new BrowserWindow({
   frame: false,

    minWidth: 1022,

    minHeight: 670,

    webPreferences: {

      nodeIntegration: true,// 打开 node 选项

      contextIsolation: false // v12 中关闭此选项以获得在窗口中使用 node 的能力

    }

 })


   tray = new Tray(path.join(__dirname, 'src/assets/images/tray.ico'));
   menu = [
    {
      label: '显示主窗口',
      id: 'show-window',
      enabled: !win.show,
      click() {
        win.show();
      }
    },
    {
      label: '退出',
      role: 'quit'
    }
   ];
  menu = Menu.buildFromTemplate(menu);
  // 给系统托盘设置菜单
  tray.setContextMenu(menu);

  win.loadURL('http://localhost:3000/');

}



app.whenReady().then(() => {

  createWindow();


  // 开发环境安装调式工具
  if (isDev) {
    installExtension(REDUX_DEVTOOLS)
    .then((name) => console.log(`Added Extension:  ${name}`))
    .catch((err) => console.log('An error occurred: ', err));

  installExtension(REACT_DEVELOPER_TOOLS)
    .then((name) => console.log(`Added Extension:  ${name}`))
    .catch((err) => console.log('An error occurred: ', err));
  }

  // 窗口最小化
  ipcMain.on("minimize", () => {
    win.minimize()
  });
  // 窗口最大化
  ipcMain.on("maximize", () => {
    win.maximize()
  });
  // 窗口恢复化
  ipcMain.on("unmaximize", () => {
    win.unmaximize()
  });
  // 缩小到托盘
  ipcMain.on("close-win", e => {
    e.preventDefault();
    win.hide();
  });

  // 托盘图标被双击
  tray.on('double-click', () => {
    // 显示窗口
    win.show();
  });

  // 窗口隐藏
  win.on('hide', () => {
    // 启用菜单的显示主窗口项
    menu.getMenuItemById('show-window').enabled = true;
    // 重新设置系统托盘菜单
    tray.setContextMenu(menu);
  });

  // 窗口显示
  win.on('show', () => {
    // 禁用显示主窗口项
    menu.getMenuItemById('show-window').enabled = false;
    // 重新设置系统托盘菜单
    tray.setContextMenu(menu);
  });
});
